﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using TimeTravel.Commons;
using TimeTravel.Components;
using TimeTravel.Extentions;
using TimeTravel.IData;

namespace TimeTravel.SqlServer
{
    public class SysLogData : ISysLogData
    {
        #region Fields

        private static readonly SqlHelper DbHelper = new SqlHelper();
        private static readonly string[] Columns = { "[id]","[logdate]", "[thread]", "[loglevel]", "[logger]","[message]","[exception]" };

        #endregion

        #region Implementation of IDataBase<SysLogInfo>

        /// <summary>
        /// 添加记录（未实现，由Log4net记录）
        /// </summary>
        public int Add(SysLogInfo t)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 删除记录（未实现）
        /// </summary>
        /// <param name="id"></param>
        public void Delete(int id)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 更新记录（未实现）
        /// </summary>
        /// <param name="t"></param>
        public void Update(SysLogInfo t)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        public IList<SysLogInfo> GetAll()
        {
            var strSql = new StringBuilder();
            strSql.AppendFormat("select {0} from SysLog ", String.Join(",", Columns));
            strSql.Append("where DeleteFlag = 0;");
            var result = DbHelper.ExecuteObjectList(strSql.ToString(), DataReaderParser);
            return result.ToList();
        }

        /// <summary>
        /// 根据条件获取
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public RecordSet<SysLogInfo> GetBySearch(PageQueryInfo query)
        {
            if(query == null) return new RecordSet<SysLogInfo>();
            return DbHelper.ExecutePaging("SysLog", query, DataReaderParser, Columns);
        }

        /// <summary>
        /// 获取详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public SysLogInfo GetOne(int id)
        {
            if (id == 0) return null;
            var strSql = new StringBuilder();
            strSql.AppendFormat("select {0} from SysLog ", String.Join(",", Columns));
            strSql.Append("where [id] = @id;");
            SqlParameter[] parameters = {
                                            new SqlParameter("@id", SqlDbType.Int)
                                        };
            parameters[0].Value = id;
            return DbHelper.ExecuteObject(CommandType.Text, strSql.ToString(), DataReaderParser, parameters);
        }

        /// <summary>
        /// 删除指定区间内的日志
        /// </summary>
        /// <param name="start">开始时间（时间戳格式）</param>
        /// <param name="end">结束时间（时间戳格式）</param>
        public void DeleteBatch(int start, int end)
        {
            if (start >= end) return;

            var strSql = new StringBuilder();
            strSql.Append("update SysLog set DeleteFlag = 1 ");
            strSql.Append("where logdate>=@start and logdate<=@end and DeleteFlag =0 ;");
            SqlParameter[] parameters = {
                                            new SqlParameter("@start", SqlDbType.Int, start),
                                            new SqlParameter("@end", SqlDbType.Int, end)
                                        };
            parameters[0].Value = start;
            parameters[1].Value = end;
            DbHelper.ExecuteNonQuery(CommandType.Text, strSql.ToString(), parameters);
        }

        /// <summary>
        /// 获取总数
        /// </summary>
        /// <returns></returns>
        public int GetTotalCount()
        {
            var strSql = new StringBuilder();
            strSql.Append("select count(id) from SysLog ");
            strSql.Append("where DeleteFlag = 0;");
            var result = DbHelper.ExecuteScalar(CommandType.Text, strSql.ToString());
            return result == null ? 0 : Convert.ToInt32(result);
        }

        #endregion

        #region BuildNavMenuObject

        /// <summary>
        /// 从DataReader中构建对象
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        private SysLogInfo DataReaderParser(IDataReader reader)
        {
            var sysLog = new SysLogInfo
                             {
                                 ID = reader.GetInt32("id"),
                                 LogDate = reader.GetString("logdate"),
                                 Thread = reader.GetString("thread"),
                                 LogLevel = reader.GetString("loglevel"),
                                 Logger = reader.GetString("logger"),
                                 Message = reader.GetString("message"),
                                 Exception = reader.GetString("exception")
                             };
            return sysLog;
        }

        #endregion
    }
}
